import Vue from "vue";
import Message from "./components/Message.vue";

let MessageConstructor = Vue.extend(Message);
const messagePipe = [];
let zIndex = 2010; // 初始属性
let currentMessageCount = 0;

const MessageInstance = function ({ text, type, duration = 2000 }) {
  let timer = null;
  const defaultTop = 64; // px

  const instance = new MessageConstructor({
    data: { text, type, duration },
  });
  const el = instance.$mount().$el;

  timer = setTimeout(() => {
    document.body.removeChild(el);
    if (timer) {
      clearTimeout(timer);
      messagePipe.shift();
      if (messagePipe.length === 0) {
        currentMessageCount = 0;
      }
    }
  }, duration);
  // 根据管道计算 盒子top 位置
  let top = "80px";
  if (currentMessageCount !== 0) {
    top = 80 + currentMessageCount * defaultTop + "px";
  }
  currentMessageCount++;
  zIndex++; // 处理dom
  // 设置dom 属性
  el.setAttribute("z-index", zIndex);
  el.style.top = top;
  document.body.appendChild(el);
  messagePipe.push(timer);
};

export default MessageInstance;
